package com.hanthink.system.service.impl.label;

import com.hanthink.common.constant.HttpStatus;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.system.domain.label.LabelRecord;
import com.hanthink.system.mapper.label.LabelRecordMapper;
import com.hanthink.system.service.impl.SysUserServiceImpl;
import com.hanthink.system.service.label.ILabelRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hanthink.system.mapper.label.LabelVerificationMapper;

import java.util.*;

/**
 * -Service业务层处理
 * 
 * @author hanthink
 * @date 2023-02-07
 */
@Service
public class LabelRecordServiceImpl implements ILabelRecordService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private LabelRecordMapper labelRecordMapper;

    /**
     * 查询-
     * 
     * @param id -ID
     * @return -
     */
    @Override
    public LabelRecord selectLabelRecordById(Long id)
    {
        return labelRecordMapper.selectLabelRecordById(id);
    }

    /**
     * 查询-列表
     * 
     * @param labelRecord -
     * @return -
     */
    @Override
    public List<LabelRecord> selectLabelRecordList(LabelRecord labelRecord)
    {
        return labelRecordMapper.selectLabelRecordList(labelRecord);
    }


    /**
     * 查询App
     *
     * @param labelRecord -
     * @return -
     */
    @Override
    public List<LabelRecord> getAppList(LabelRecord labelRecord) {
        return labelRecordMapper.getAppList(labelRecord);
    }

    /**
     * 新增-
     * 
     * @param labelRecord -
     * @return 结果
     */
    @Override
    public int insertLabelRecord(LabelRecord labelRecord, String loginUser)
    {
        String isDelete = "0";
        labelRecord.setCreator(loginUser);
        labelRecord.setCreatdatetime(new Date());

        LabelRecord queryLabel = replaceMethod(labelRecord);
        int result = 0;
        List<LabelRecord> labels = labelRecordMapper.getList(queryLabel);
        if(labels.size() > 0){
            //数据库已有数据 抛出
            throw new CustomException("新增数据已存在，请选择更新数据");
        }else {
            //新增
            result = labelRecordMapper.insertLabelRecord(replaceMethod(labelRecord));
        }
        return result;
    }

    public int insertLabel(LabelRecord labelRecord, String loginUser)
    {
        String isDelete = "0";
        labelRecord.setCreator(loginUser);
        labelRecord.setCreatdatetime(new Date());

        return labelRecordMapper.insertLabelRecord(replaceMethod(labelRecord));
    }

    /**
     * 修改-
     *
     * @param labelRecord -
     * @param loginUser
     * @return 结果
     */
    @Override
    public int updateLabelRecord(LabelRecord labelRecord, String loginUser)
    {

        return labelRecordMapper.updateLabelRecord(replaceMethod(labelRecord));
    }




    /**
     * 批量删除-
     * 
     * @param ids 需要删除的-ID
     * @return 结果
     */
    @Override
    public int deleteLabelRecordByIds(Long[] ids, String userName)
    {
        return labelRecordMapper.deleteLabelRecordByIds(ids,userName);
    }

    @Override
    public String importPlan(List<LabelRecord> labelList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(labelList) || labelList.size() == 0) {
            throw new CustomException("导入计划数据不能为空！");
        }
        //成功数据
        int successNum = 0;
        //失败数据
        int failureNum = 0;
        //重复数据
        int duplicateNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder duplicateMsg = new StringBuilder();
        int currentRowNum = 0;
        for (LabelRecord label : labelList) {
            //label.setStatus("1");
            currentRowNum++;
            try {
                // 校验数据信息
                if (StringUtils.isEmpty(label.getCustomer())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据客户名称不能为空");
                    continue;
                } else if (StringUtils.isEmpty(label.getProduction())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据产品名称不能为空");
                    continue;
//                } else if (StringUtils.isNull(label.getFrontlabel()) || !StringUtils.isNumeric(label.getFrontlabel())) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据前标签标签号不能为空且只能为数字类型");
//                    continue;
//                } else if (StringUtils.isEmpty(label.getBacklabel()) || !StringUtils.isNumeric(label.getBacklabel())) {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据背标签标签号不能为空且只能为数字类型");
//                    continue;
                }
                label.setCustomer(label.getCustomer().replaceAll("\\s+", ""));
                label.setProduction(label.getProduction().replaceAll("\\s+", ""));
                label.setAntifakelabel(label.getAntifakelabel().replaceAll("\\s+", ""));
                label.setBacklabel(label.getBacklabel().replaceAll("\\s+", ""));
                label.setFrontlabel(label.getFrontlabel().replaceAll("\\s+",  ""));
                //label.setCreatdatetime(label.getCreatdatetime().replaceAll("\\s+",  ""));
                label.setCreator(label.getCreator().replaceAll("\\s+",  ""));
                LabelRecord queryLabel = new LabelRecord();
                queryLabel.setCustomer(label.getCustomer());
                queryLabel.setBacklabel(label.getBacklabel());
                queryLabel.setAntifakelabel(label.getAntifakelabel());
                queryLabel.setProduction(label.getProduction());
                queryLabel.setFrontlabel(label.getFrontlabel());
                queryLabel.setCreatdatetime(label.getCreatdatetime());
                queryLabel.setCreator(label.getCreator());

                List<LabelRecord> labels = labelRecordMapper.getList(queryLabel);
                if(labels.size() > 0 && isUpdateSupport){
                    LabelRecord returnLabel = labels.get(0);
                    label.setId(returnLabel.getId());
                    this.updateLabelRecord(label,operName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、标签数据 " + label.getProduction() + " 更新成功");
                }else if(labels.size() > 0 && !isUpdateSupport){
                    //数据重复
                    duplicateNum++;
                    duplicateMsg.append("<br/>" + duplicateNum + "、第" + currentRowNum + "行数据已存在，请勾选更新按钮更新已经存在的标签数据");
                }else {
                    this.insertLabel(label,operName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、标签数据 " + label.getProduction() + " 导入成功");
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、标签数据" + label.getProduction() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }else if (duplicateNum > 0) {
            if(successNum>0){
                duplicateMsg.insert(0, "共 " + successNum + " 条数据导入成功！其中"+ duplicateNum + " 条数据导入失败，错误如下：");
            }else{
                duplicateMsg.insert(0, "很抱歉，共 " + duplicateNum + " 条数据导入失败，错误如下：");
            }
            throw new CustomException(duplicateMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Map<String,Object> getCustomerAndProduction() {
        Map<String,Object> map= new HashMap<>();
        ArrayList customerList = new ArrayList();
        ArrayList productionList = new ArrayList();
        LabelRecord labelRecord = new LabelRecord();
        List<LabelRecord> list = this.getAppList(labelRecord);
        if(list.size()>0){
            for (LabelRecord item:list) {
                customerList.add(item.getCustomer());
                productionList.add(item.getProduction());
            }
            map.put("customerList", method(customerList));
            map.put("productionList",method(productionList));
            map.put("code", HttpStatus.SUCCESS);
            map.put("msg","查询成功");
        }else{
            map.put("code", HttpStatus.ERROR);
            map.put("msg","未查询到标签信息");
        }
        return map;
    }

    @Override
    public int changeStatusByIds(Long[] ids,String userName) {
        Date modifydate = new Date();
        return labelRecordMapper.changeStatusByIds(ids,userName,modifydate);
    }

    /**
     * 自定义去重
     *
     * @param list
     * @return
     */
    private static ArrayList<String> method(ArrayList<String> list) {
        ArrayList<String> listTemp = new ArrayList<>();
        for(int i=0;i<list.size();i++){
            if(!listTemp.contains(list.get(i))){
                listTemp.add(list.get(i));
            }
        }
        return listTemp;
    }

    /**
     * 自定义去空格
     *
     * @param label
     * @return
     */
    private static LabelRecord replaceMethod(LabelRecord label) {
        if(StringUtils.isNotNull(label.getFrontlabel())){
            label.setFrontlabel(label.getFrontlabel().replaceAll("\\s+",  ""));
        } else if (StringUtils.isNotNull(label.getCustomer())) {
            label.setCustomer(label.getCustomer().replaceAll("\\s+", ""));
        } else if (StringUtils.isNotNull(label.getProduction())) {
            label.setProduction(label.getProduction().replaceAll("\\s+", ""));
        } else if (StringUtils.isNotNull(label.getBacklabel())) {
            label.setBacklabel(label.getBacklabel().replaceAll("\\s+", ""));
        } else if (StringUtils.isNotNull(label.getAntifakelabel())) {
            label.setAntifakelabel(label.getAntifakelabel().replaceAll("\\s+", ""));
        }
        return label;
    }
}
